package com.geek.factory.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.MessageConstant;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.dto.UserAddDTO;
import com.geek.factory.entity.Role;
import com.geek.factory.entity.User;
import com.geek.factory.entity.UserRole;
import com.geek.factory.result.Result;
import com.geek.factory.security.LoginUser;
import com.geek.factory.service.RoleService;
import com.geek.factory.service.UserRoleService;
import com.geek.factory.service.UserService;
import com.geek.factory.utils.JwtHelper;
import com.geek.factory.vo.PageQueryVO;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

import static com.geek.factory.constant.SuccessConstant.FAIL;
import static com.geek.factory.constant.SuccessConstant.SUCCESS;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-06-19
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    //前端发送请求，请求头中必须携带token才能放行  config.headers.Authorization = `Bearer ${accessToken}`;
    @ApiOperation("获取用户信息")
    @GetMapping("info")
    public Result getUserInfo(@ApiParam("请求头中携带Authorization") @RequestHeader("Authorization")String authorization){
        //SpringSecurity 使用之后
        //获取认证信息 (管理员信息、账号状态、权限等)
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        if(!ObjectUtils.isEmpty(loginUser)){
            User user = loginUser.getUser();
            if(user!=null){
                return new Result(SuccessConstant.SUCCESS , MessageConstant.GET_LOGIN_USER_SUCCESS, user);
            }
        }
        return new Result(SuccessConstant.FAIL , MessageConstant.GET_LOGIN_USER_FAIL);
//        if(StringUtils.hasLength(authorization)){
//            String token = authorization.substring(7);
//            log.info("token:{}" , token);
//            Long userId = JwtHelper.getUserId(token);
//            User user = userService.getById(userId);
//            if(user!=null){
//                return new Result(SUCCESS , MessageConstant.GET_LOGIN_USER_SUCCESS, user);
//            }
//        }
//        return new Result(FAIL , MessageConstant.GET_LOGIN_USER_FAIL);
    }


    @ApiParam("分页查询用户列表")
    @GetMapping("page")
    public Result page(@ApiParam("分页请求参数") PageQueryVO vo){
        Page<User> userPage = userService.page(vo);
        if(userPage!=null && userPage.getTotal()>0){
            return new Result(SUCCESS , MessageConstant.GET_USER_SUCCESS, userPage);
        }
        return new Result(FAIL , MessageConstant.GET_USER_FAIL);
    }

    @ApiParam("通过ID查询用户信息")
    @GetMapping("{id}")
    public Result page(@ApiParam("用户ID") @PathVariable("id") Long id){
        User user = userService.getById(id);
        if(user!=null){
            return new Result(SUCCESS , MessageConstant.GET_USER_SUCCESS, user);
        }
        return new Result(FAIL , MessageConstant.GET_USER_FAIL);
    }

@ApiModelProperty("分页查询用户列表")
@GetMapping("list")
public Result findPage(
        @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
        @RequestParam(value = "size", required = false, defaultValue = "10") Integer size,
        @RequestParam(value = "name", required = false) String name
) {
    Page<User> page = new Page<>(current, size);
    LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
    if (StringUtils.hasLength(name)) {
        wrapper.like(User::getUsername, name);
    }
    wrapper.orderByAsc(User::getId);

    Page<User> userPage = userService.page(page, wrapper);

    // 查询所有 userId
    List<Integer> userIds = userPage.getRecords().stream().map(User::getId).collect(Collectors.toList());
    // 查询 user_role
    List<UserRole> userRoles = userRoleService.list(new LambdaQueryWrapper<UserRole>().in(UserRole::getUserId, userIds));
    // 查询所有角色
    List<Role> roles = roleService.list();
    Map<Integer, Role> roleMap = roles.stream().collect(Collectors.toMap(Role::getId, r -> r));
    // 组装 userId -> List<Role>
    Map<Integer, List<Role>> userRoleMap = new HashMap<>();
    for (UserRole ur : userRoles) {
        userRoleMap.computeIfAbsent(ur.getUserId(), k -> new ArrayList<>()).add(roleMap.get(ur.getRoleId()));
    }
    // 填充到 user
//    for (User u : userPage.getRecords()) {
//        u.setRoles(userRoleMap.getOrDefault(u.getId(), new ArrayList<>()));
//    }
    for (User u : userPage.getRecords()) {
        List<Role> roleList = userRoleMap.getOrDefault(u.getId(), new ArrayList<>());
        u.setRoles(new HashSet<>(roleList)); // 转换为 Set
    }


    if (userPage != null && userPage.getTotal() > 0) {
        return new Result(SUCCESS, MessageConstant.GET_USER_SUCCESS, userPage);
    }
    return new Result(FAIL, MessageConstant.GET_USER_FAIL);
}

@PostMapping("add")
public Result add(@RequestBody User user) {
    // 处理角色ID转换
    if(user.getRoleIds() != null && !user.getRoleIds().isEmpty()) {
        user.setRoleId(user.getRoleIds().get(0)); // 取第一个作为主要角色
    }
    userService.save(user);
    // 保存用户角色关系
    if (user.getRoleIds() != null) {
        userRoleService.saveBatch(
                user.getRoleIds().stream()
                        .map(roleId -> new UserRole(null, user.getId(), roleId))
                        .collect(Collectors.toList())
        );
    }
    return new Result(SUCCESS, "添加成功");
}

@ApiModelProperty("修改用户")
@PutMapping("update")
public Result update(@RequestBody User user, @RequestParam(required = false) Boolean onlyPassword) {
    // 如果只是修改密码
    if (Boolean.TRUE.equals(onlyPassword)) {
        userService.updateById(user);
        return new Result(SUCCESS, "密码修改成功");
    }

    // 原逻辑处理其他修改
    if(user.getRoleIds() != null && !user.getRoleIds().isEmpty()) {
        user.setRoleId(user.getRoleIds().get(0));
    }

    userService.updateById(user);

    // 只有角色ID不为空时才处理角色关系
    if (user.getRoleIds() != null) {
        userRoleService.remove(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId, user.getId()));

        if (!user.getRoleIds().isEmpty()) {
            userRoleService.saveBatch(
                    user.getRoleIds().stream()
                            .map(roleId -> new UserRole(null, user.getId(), roleId))
                            .collect(Collectors.toList())
            );
        }
    }
    return new Result(SUCCESS, "修改成功");
}
//@PutMapping("update")
//public Result update(@RequestBody User user) {
//    // 处理角色ID转换（如果是单角色系统）
//    if(user.getRoleIds() != null && !user.getRoleIds().isEmpty()) {
//        user.setRoleId(user.getRoleIds().get(0)); // 取第一个作为主要角色
//    }
//
//    // 更新用户基本信息
//    userService.updateById(user);
//
//    // 先删除原有角色关系
//    userRoleService.remove(new LambdaQueryWrapper<UserRole>()
//            .eq(UserRole::getUserId, user.getId()));
//
//    // 保存新的角色关系（支持多角色）
//    if (user.getRoleIds() != null && !user.getRoleIds().isEmpty()) {
//        userRoleService.saveBatch(
//                user.getRoleIds().stream()
//                        .map(roleId -> new UserRole(null, user.getId(), roleId))
//                        .collect(Collectors.toList())
//        );
//    }
//    return new Result(SUCCESS, "修改成功");
//}

    @ApiModelProperty("删除用户")
    @DeleteMapping("{id}")
    public Result delete(@PathVariable("id") Integer id) {
        if (userService.removeById(id)) {
            return new Result(SUCCESS, "删除成功");
        }
        return new Result(FAIL, "删除失败");
    }
    @ApiOperation("下载设置模板")
    @GetMapping("download")
    public void download(HttpServletResponse response)  {
        //1.找到模板文件
        File file = null;
        try {
            file = ResourceUtils.getFile("classpath:templates/ordersetting_template.xlsx");
        } catch (FileNotFoundException e) {
            log.warn("模板文件不存在！");
            return;
        }

        //2.响应
        if(file!=null && file.isFile()){
            String filename = file.getName();

            //设置响应
            response.reset();
            response.setContentType("application/force-download");
            response.setCharacterEncoding("utf-8");
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);

            //边读边写
            try (
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                    BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            ){
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = bis.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                    bos.flush();
                }
            } catch (IOException e) {
                log.error("模板下载出错： {}" , e.getMessage());
            }
        }
    }


    @PostMapping("/upload")
    @ApiOperation("批量导入用户")
    public Result upload(@RequestParam("file") MultipartFile file) {
        try {
            boolean success = userService.upload(file);
            if (success) {
                return new Result(SUCCESS, "用户导入成功");
            } else {
                return new Result(FAIL, "用户导入失败");
            }
        } catch (Exception e) {
            log.error("用户导入失败", e);
            return new Result(FAIL, "用户导入失败：" + e.getMessage());
        }
    }

    @GetMapping("/template")
    @ApiOperation("下载用户导入模板")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            userService.downloadTemplate(response);
        } catch (Exception e) {
            log.error("模板下载失败", e);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            try {
                response.getWriter().write("{\"message\":\"模板下载失败：" + e.getMessage() + "\"}");
            } catch (IOException ex) {
                log.error("写入错误响应失败", ex);
            }
        }
    }


}
